package com.zyf.project.kvdb.protocol.handler;

import com.zyf.project.kvdb.protocol.proto.Message;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Zhou Yifan
 */
@ChannelHandler.Sharable
public class KVDBConnectionHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(KVDBConnectionHandler.class);

    private final KVDBHandler kvdbHandler;

    public KVDBConnectionHandler(KVDBHandler kvdbHandler) {
        this.kvdbHandler = kvdbHandler;
    }

    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {
        kvdbHandler.connected(channelHandlerContext);
    }

    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        try {
            kvdbHandler.receive(channelHandlerContext, (Message) msg);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext channelHandlerContext) throws Exception {
        LOGGER.debug("channel inactive");
        kvdbHandler.disconnected(channelHandlerContext);
        channelHandlerContext.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause) throws Exception {
        LOGGER.debug("uncaught exception", cause);
        kvdbHandler.disconnected(channelHandlerContext);
        channelHandlerContext.close();
    }

}
